<template>
  <div class="venue-form">
    <el-page-header @back="goBack" class="page-header">
      <template #content>
        <span class="page-title">{{ isEdit ? '编辑场地' : '新建场地' }}</span>
      </template>
    </el-page-header>

    <el-card class="form-card" v-loading="loading">
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
      >
        <el-divider content-position="left">基本信息</el-divider>
        
        <el-form-item label="场地名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入场地名称" />
        </el-form-item>

        <el-form-item label="场地描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入场地描述"
          />
        </el-form-item>

        <el-form-item label="场地类别" prop="category">
          <el-select v-model="form.category" placeholder="请选择场地类别">
            <el-option label="足球场" value="football" />
            <el-option label="篮球场" value="basketball" />
            <el-option label="羽毛球馆" value="badminton" />
            <el-option label="网球场" value="tennis" />
            <el-option label="游泳池" value="swimming" />
            <el-option label="健身房" value="gym" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>

        <el-form-item label="运动类型" prop="sportTypes">
          <el-input 
            v-model="form.sportTypes" 
            placeholder="多个类型用逗号分隔，如：足球,篮球"
          />
        </el-form-item>

        <el-divider content-position="left">地址信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="城市" prop="city">
              <el-input v-model="form.city" placeholder="请输入城市" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区域" prop="district">
              <el-input v-model="form.district" placeholder="请输入区域" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input-number 
                v-model="form.longitude" 
                :precision="6"
                :step="0.000001"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input-number 
                v-model="form.latitude" 
                :precision="6"
                :step="0.000001"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">联系方式</el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入电子邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">场地信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="容纳人数" prop="capacity">
              <el-input-number v-model="form.capacity" :min="1" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场地面积" prop="area">
              <el-input-number 
                v-model="form.area" 
                :min="0" 
                :precision="2"
                style="width: 100%"
              >
                <template #append>平方米</template>
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="设施设备" prop="facilities">
          <el-input 
            v-model="form.facilities" 
            type="textarea"
            :rows="3"
            placeholder="请输入设施设备，多个用逗号分隔"
          />
        </el-form-item>

        <el-form-item label="营业时间" prop="businessHours">
          <el-input 
            v-model="form.businessHours" 
            placeholder="例如：周一至周日 08:00-22:00"
          />
        </el-form-item>

        <el-form-item label="价格信息" prop="priceInfo">
          <el-input 
            v-model="form.priceInfo" 
            type="textarea"
            :rows="3"
            placeholder="请输入价格信息"
          />
        </el-form-item>

        <el-form-item label="封面图片" prop="coverImage">
          <el-input 
            v-model="form.coverImage" 
            placeholder="请输入封面图片URL"
          />
          <div class="form-tip">提示：暂时请直接输入图片URL，后续会添加图片上传功能</div>
        </el-form-item>

        <el-form-item label="场地状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="active">营业中</el-radio>
            <el-radio label="inactive">暂停营业</el-radio>
            <el-radio label="maintenance">维护中</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            {{ isEdit ? '保存' : '创建' }}
          </el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { venueApi } from '@/api/venue'

const route = useRoute()
const router = useRouter()

const formRef = ref(null)
const loading = ref(false)
const submitting = ref(false)

const isEdit = computed(() => route.path.includes('/edit/'))
const venueId = computed(() => route.params.id)

const form = reactive({
  name: '',
  description: '',
  category: '',
  sportTypes: '',
  city: '',
  district: '',
  address: '',
  longitude: null,
  latitude: null,
  phone: '',
  email: '',
  capacity: 50,
  area: null,
  facilities: '',
  businessHours: '',
  priceInfo: '',
  coverImage: '',
  status: 'active'
})

const rules = {
  name: [
    { required: true, message: '请输入场地名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择场地类别', trigger: 'change' }
  ],
  city: [
    { required: true, message: '请输入城市', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  capacity: [
    { required: true, message: '请输入容纳人数', trigger: 'blur' }
  ]
}

onMounted(() => {
  if (isEdit.value) {
    loadVenueData()
  }
})

const loadVenueData = async () => {
  loading.value = true
  try {
    const data = await venueApi.getVenueDetail(venueId.value)
    Object.assign(form, data)
  } catch (error) {
    console.error('加载场地信息失败:', error)
    ElMessage.error('加载场地信息失败')
  } finally {
    loading.value = false
  }
}

const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    submitting.value = true

    try {
      if (isEdit.value) {
        await venueApi.updateVenue(venueId.value, form)
        ElMessage.success('场地更新成功')
      } else {
        await venueApi.createVenue(form)
        ElMessage.success('场地创建成功')
      }
      router.push('/venues')
    } catch (error) {
      console.error('操作失败:', error)
      ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
    } finally {
      submitting.value = false
    }
  })
}

const goBack = () => {
  router.back()
}
</script>

<style scoped>
.venue-form {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
}

.form-card {
  max-width: 900px;
  margin: 0 auto;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

:deep(.el-divider__text) {
  font-weight: 600;
  color: #303133;
}
</style>

